package saas.dev.cloud.util.test;

import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName : RecursionUtil
 * @Author : y1
 * @Date: 2022/5/19 16:49
 * @Description : 递归工具类
 */
public class RecursionUtil {
    /**
     * 递归入口
     *
     * @param sqlList  数据库查询出来的List集合
     * @param clazz    转换类
     * @param parentId 父id
     * @return
     */
    public static List<? extends BaseBeanTree> call(List<?> sqlList, Class<? extends BaseBeanTree> clazz, Serializable parentId) {
        List<? extends BaseBeanTree> collect = sqlList.stream().map(i -> getBaseBeanTree(clazz, i)).collect(Collectors.toList());
        return collect.stream().filter(m -> m.getParentId().equals(parentId)).peek(
                (m) -> m.setChildList(getChildren(m, collect))
        ).collect(Collectors.toList());
    }

    private static BaseBeanTree getBaseBeanTree(Class<? extends BaseBeanTree> clazz, Object i) {
        BaseBeanTree baseBeanTree = null;
        try {
            baseBeanTree = clazz.newInstance();
            BeanUtils.copyProperties(i, baseBeanTree);
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return baseBeanTree;
    }

    /**
     * 递归
     *
     * @param root
     * @param trees
     * @return
     */
    private static List<? extends BaseBeanTree> getChildren(BaseBeanTree root, List<? extends BaseBeanTree> trees) {
        return trees.stream()
                .filter(m -> Objects.equals(m.getParentId(), root.getId()))
                .peek(m -> m.setChildList(getChildren(m, trees))
                ).collect(Collectors.toList());
    }
}
